﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;

/// <summary>
/// 实现post,get
/// </summary>
public class HttpHelper
{

        #region 创建get请求
		/// <summary>
		///  创建get请求
		/// </summary>
		/// <param name="url">请求的网址</param>
		/// <returns></returns>
		public static string CreateGetHttpText (string url)
		{
				HttpWebRequest request = null;
				request = WebRequest.Create (url) as HttpWebRequest;
				request.Method = "GET";
				return GetResponseString (request.GetResponse () as HttpWebResponse);
		}
        #endregion

        #region 创建post请求(可传文件)
		/// <summary>
		/// 创建post请求(可传文件)
		/// </summary>
		/// <param name="url">请求的网址</param>
		/// <param name="param">参数哈希表 IDictionary</param>
		/// <param name="fileByte">文件二进制</param>
		/// <returns>服务器返回的信息 string</returns>
		public static string CreatePostHttpText (string url, IDictionary<object, object> param, byte[] fileByte = null, string type = "text/plain", string mkey="img")
		{
				string boundary = "---------------------------" + DateTime.Now.Ticks.ToString ("x");
				byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes ("\r\n--" + boundary + "\r\n");

				HttpWebRequest wr = (HttpWebRequest)WebRequest.Create (url);
				wr.ContentType = "multipart/form-data; boundary=" + boundary;
				wr.Method = "POST";
				wr.KeepAlive = true;
            
				wr.Credentials = System.Net.CredentialCache.DefaultCredentials;

				Stream rs = wr.GetRequestStream ();
				string responseStr = null;

				string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
				foreach (string key in param.Keys) {
						rs.Write (boundarybytes, 0, boundarybytes.Length);
             
						string formitem = string.Format (formdataTemplate, key, param [key]);
						byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes (formitem);
						rs.Write (formitembytes, 0, formitembytes.Length);
				}
				rs.Write (boundarybytes, 0, boundarybytes.Length);

				string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
				if (fileByte != null) {
						string header = string.Format (headerTemplate, mkey, fileByte, type);//image/jpeg
						byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes (header);              
						rs.Write (headerbytes, 0, headerbytes.Length);
						rs.Write (fileByte, 0, fileByte.Length);
				}

				byte[] trailer = System.Text.Encoding.ASCII.GetBytes ("\r\n--" + boundary + "--\r\n");
				rs.Write (trailer, 0, trailer.Length);
				rs.Close ();

				WebResponse wresp = null;
				try {
						wresp = wr.GetResponse ();
						Stream stream2 = wresp.GetResponseStream ();
						StreamReader reader2 = new StreamReader (stream2);
						responseStr = reader2.ReadToEnd ();
				} catch (Exception) {
					
						if (wresp != null) {
								wresp.Close ();
								wresp = null;
						}
			    
				} finally {
						wr = null;
				}
				return responseStr;
		}
        #endregion

        #region Post With Pic
		private string HttpPost (string url, IDictionary<object, object> param, string filePath)
		{
     
				string boundary = "---------------------------" + DateTime.Now.Ticks.ToString ("x");
				byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes ("\r\n--" + boundary + "\r\n");

				HttpWebRequest wr = (HttpWebRequest)WebRequest.Create (url);
				wr.ContentType = "multipart/form-data; boundary=" + boundary;
				wr.Method = "POST";
				wr.KeepAlive = true;
				wr.Credentials = System.Net.CredentialCache.DefaultCredentials;

				Stream rs = wr.GetRequestStream ();
				string responseStr = null;

				string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
				foreach (string key in param.Keys) {
						rs.Write (boundarybytes, 0, boundarybytes.Length);
						string formitem = string.Format (formdataTemplate, key, param [key]);
						byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes (formitem);
						rs.Write (formitembytes, 0, formitembytes.Length);
				}
				rs.Write (boundarybytes, 0, boundarybytes.Length);

				string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
				string header = string.Format (headerTemplate, "img", filePath, "text/plain");
				byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes (header);
				rs.Write (headerbytes, 0, headerbytes.Length);

				FileStream fileStream = new FileStream (filePath, FileMode.Open, FileAccess.Read);
				byte[] buffer = new byte[4096];
				int bytesRead = 0;
				while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0) {
						rs.Write (buffer, 0, bytesRead);
				}
				fileStream.Close ();

				byte[] trailer = System.Text.Encoding.ASCII.GetBytes ("\r\n--" + boundary + "--\r\n");
				rs.Write (trailer, 0, trailer.Length);
				rs.Close ();

				WebResponse wresp = null;
				try {
						wresp = wr.GetResponse ();
						Stream stream2 = wresp.GetResponseStream ();
						StreamReader reader2 = new StreamReader (stream2);
						responseStr = reader2.ReadToEnd ();
						// logger.Debug(string.Format("File uploaded, server response is: {0}", responseStr));
				} catch (Exception) {
					
						//  logger.Error("Error uploading file", ex);
						if (wresp != null) {
								wresp.Close ();
								wresp = null;
						}
				} finally {
						wr = null;
				}
				return responseStr;
		}
        #endregion

        #region 请求的数据转成string
		/// <summary>
		/// 请求的数据转成string
		/// </summary>
		/// <param name="webresponse"></param>
		/// <returns></returns>
		private static string GetResponseString (HttpWebResponse webresponse)
		{
				using (Stream s = webresponse.GetResponseStream()) {
						StreamReader reader = new StreamReader (s, Encoding.UTF8);
						return reader.ReadToEnd ();

				}
		}
        #endregion

}
